package com.xiao.sulingother.controller.qr;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.common.utils.StringUtils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.xiao.sulingother.conster.RedisConster;
import com.xiao.sulingpublic.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author: 1322127758@qq.com
 * @date: 2022/3/31 13:00
 * @作用: 生成二维码
 */
@RequestMapping("/qrcode")
@RestController
public class QRCodeWriterController {
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 访问nginx静态文件的路径
     */
    @Value("${spring.my.nginx.url}")
    private String url;

    /**
     * 获取订单收货状态, 如果redis中有数据就是发布者收货了,  每个用户都会3秒发一次请求获取状态,所以需要高并发
     * @param userName :领取人号
     * @param orderSn  :订单号
     * @return :返回订单状态
     */
    @RequestMapping("/receipt/state")
    public R getReceiptState(@RequestParam("userName") String userName, @RequestParam("orderSn") String orderSn){

        if(StringUtils.isEmpty(userName) || StringUtils.isEmpty(orderSn)){
            return R.error("参数数据为null");
        }

        // 用户收货后 将状态保存在redis中的key  前缀 + 领取人 + 订单号
        String s = redisTemplate.opsForValue().get(RedisConster.RE_STATE_KEY + userName + "-" + orderSn);
        if (!StringUtils.isEmpty(s)){
            return R.ok().put("state",s);
        }

       return R.error("还未收货");
    }



    /**
     * 生成收货二维码
     * 二维码包含 领取人号,订单号,code
     * @param param: 接收领取人号,订单号
     * @throws Exception
     */
    @RequestMapping("/production")
    public String getQRCode(@RequestParam Map<String,Object> param) throws Exception {
        String userName = (String) param.get("userName");
        String orderSn = (String) param.get("orderSn");
        if(StringUtils.isEmpty(userName) || StringUtils.isEmpty(orderSn)){
            return "";
        }
        //生存code
        String code = UUID.randomUUID().toString().replace("-", "").substring(0, 10);
        //保存code保存在redis中
        String key = RedisConster.QR_CODE_KEY + userName + "-" + orderSn;
        redisTemplate.opsForValue().set(key, code + "-" + System.currentTimeMillis(), 6, TimeUnit.DAYS);

        param.put("code",code);
        String content = JSON.toJSONString(param);
        int weight = 200;
        int height = 200;
        //二维码保存的路径
        String time = new SimpleDateFormat("yyyy-MM-dd").format(new Date()).toString();
        String uuid = UUID.randomUUID().toString().replace("-","");
        String picturePath = "/root/docker/nginx/html/suling/img/" + time;


        QRCodeWriter qrCodeWriter=new QRCodeWriter();
        BitMatrix bitMatrix;

        try {
            bitMatrix=qrCodeWriter.encode(content, BarcodeFormat.QR_CODE,weight,height);
        }catch (Exception e){
            throw new Exception("生成二维码出错:"+e.getMessage());
        }

        //没有目录先创建目录
        File file =new File(picturePath);
        //如果文件夹不存在则创建
        if  (!file.exists()  && !file.isDirectory())
        {
            file.mkdir();
        }
        Path path= FileSystems.getDefault().getPath(file.getPath() + "/" + uuid + ".png");
        System.out.println("路径为:"+path);



        try {
            MatrixToImageWriter.writeToPath(bitMatrix,"PNG",path);
        }catch (IOException e){
            throw new Exception("二维码写入错误!"+e.getMessage());
        }

        // 返回图片访问的;路径
        return url + "suling/img/" + time + "/" + uuid + ".png";
    }
}
